﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace NMbsDuplex.ProtocalBuffer.Bifrost
{
    public static partial class HolySword
    {
        /// <summary>
        /// 转化`文件`为人类可识别的大小单元
        /// </summary>
        /// <param name="fileUrl"></param>
        /// <returns></returns>
        public static string CalcFileSize(string fileUrl)
        {
            if (!File.Exists(fileUrl))
            {
                if (Directory.Exists(fileUrl))
                    throw new IOException("Dir不可以被当做File解析");
                throw new IOException("Open Error:~ 文件不存在");
            }
            else
            {
                using (var fs = new FileStream(fileUrl, FileMode.Open))
                {
                    long FLen = fs.Length;
                    string UnitName = YouTube(FLen);

                    // 计算 bytes[][][][]文件大小
                    Weightor(FLen);
                    return UnitName;
                }
            }
        }

        /// 将`字节流尺寸`切割为人类可以理解的文件大小尺寸 单元字符串可以被无限扩展
        public static string YouTube(long FLen)
        {
            int stepSize = 1024, times = 0;
            float rsVal = 0.0f;
            var humaniations = new string[] { "Kb", "Mb", "Gb", "Tb" };
            string rsString = string.Empty;
            do
            {
                rsString = humaniations.ElementAt(times);
                times++;
                if (times >= humaniations.Length)
                {
                    rsString += "^+";
                    break;
                }
            } while ((rsVal = FLen / (float)Math.Pow(stepSize, times)) > stepSize);

            string expression = "`" + string.Format("[{0:F2}{1}", rsVal, rsString);
            return expression + "|" + FLen + "字节]";
        }

        public static byte[] Weightor(long Number)
        {
            byte[] result1 = BitConverter.GetBytes(Number);
            result1.ToList().ForEach(b =>
            {
                Console.Write("[{0:X2}].", b);
            });
            long result2 = BitConverter.ToInt64(result1, 0);
            Console.WriteLine("BitConverter.ToInt32(result1,0) ---> " + result2);
            return result1;
        }
    }
}
